<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { register } from '@/api/auth.js'
import { useThemeStore } from '@/stores/theme'
import ToggleTheme from '@/components/ToggleTheme.vue'
import AvatarSelection from "@/components/AvatarSelection.vue";
import noAvatar from '@/assets/images/no-avatar.png'
import PuzzleCode from "@/components/PuzzleCode.vue";

const router = useRouter()
const themeStore = useThemeStore()

// 注册表单数据
const registerForm = reactive({
  avatar: '',
  nickname: '',
  username: '',
  password: '',
  confirmPassword: '',
  sex: '男',
  age: 18,
  email: '',
  phone: '',
  slideVerify: false
})

// 表单验证规则
const rules = {
  avatar: [
    { required: true, message: '请上传头像', trigger: 'blur' },
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 150, message: '年龄必须在 1 到 150 之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 加载状态
const loading = ref(false)

// 表单引用
const formRef = ref(null)

// 处理注册
const handleRegister = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (!registerForm.slideVerify) {
        ElMessage.warning('请完成滑块验证')
        return
      }
      loading.value = true
      try {
        // 准备注册数据
        const registerData = {
          avatar: registerForm.avatar,
          nickname: registerForm.nickname,
          username: registerForm.username,
          password: registerForm.password,
          sex: registerForm.sex,
          age: registerForm.age,
          email: registerForm.email,
          phone: registerForm.phone
        }

        const res = await register(registerData)
        if (res.code === 200) {
          ElMessage.success('注册成功，请登录')
          // 跳转到登录页
          router.push('/login')
        } else {
          ElMessage.error(res.msg || '注册失败')
        }
      } catch (error) {
        console.error('注册出错:', error)
        ElMessage.error('注册失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}

const avatarSelectionVisible = ref(false)

// 显示头像选择对话框
const showAvatarSelection = () => {
  avatarSelectionVisible.value = true
}

// 处理头像选择结果
const handleAvatarSelected = (avatarUrl) => {
  registerForm.avatar = avatarUrl
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}

// 滑块验证成功回调
const handleSlideSuccess = (x) => {
  registerForm.slideVerify = true
  ElMessage.success('验证成功')
}

// 滑块验证失败回调
const handleSlideFail = (x) => {
  registerForm.slideVerify = false
  ElMessage.warning('验证失败，请重试')
}
</script>

<template>
  <div class="register-container" :class="{ 'dark-theme': themeStore.isDark }">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="floating-shape shape-1"></div>
      <div class="floating-shape shape-2"></div>
      <div class="floating-shape shape-3"></div>
      <div class="floating-shape shape-4"></div>
    </div>

    <!-- 主题切换按钮 -->
    <div class="theme-toggle-wrapper">
      <ToggleTheme />
    </div>

    <div class="register-box">
      <div class="register-header">
        <div class="logo-section">
          <div class="logo-icon">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
              <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
              <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
            </svg>
          </div>
          <h2>AI角色扮演</h2>
        </div>
        <p>创建您的账号，开始精彩旅程</p>
      </div>

      <el-form
        ref="formRef"
        :model="registerForm"
        :rules="rules"
        label-position="top"
        class="register-form"
      >
        <!-- 两列布局容器 -->
        <div class="form-columns">
          <!-- 左列 -->
          <div class="form-column">
            <el-form-item label="头像" prop="avatar">
              <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="点击更换头像"
                  placement="top"
              >
                <el-avatar
                    :src="registerForm.avatar || noAvatar"
                    @click="showAvatarSelection"
                    style="cursor: pointer;"
                    :size="35"
                />
                <el-input v-model="registerForm.avatar" type="hidden"></el-input>
              </el-tooltip>
            </el-form-item>
            
            <el-form-item label="昵称" prop="nickname">
              <el-input
                v-model="registerForm.nickname"
                placeholder="请输入昵称"
                prefix-icon="User"
                class="glass-input"
                size="small"
              />
            </el-form-item>
            
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                prefix-icon="Avatar"
                class="glass-input"
                size="small"
              />
            </el-form-item>
            
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                show-password
                class="glass-input"
                size="small"
              />
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请确认密码"
                prefix-icon="Lock"
                show-password
                class="glass-input"
                size="small"
              />
            </el-form-item>
          </div>
          
          <!-- 右列 -->
          <div class="form-column">
            <div class="form-row-inline">
              <el-form-item label="性别" prop="sex" class="form-item-inline">
                <el-radio-group v-model="registerForm.sex" class="glass-radio-group" size="small">
                  <el-radio value="男" class="glass-radio">男</el-radio>
                  <el-radio value="女" class="glass-radio">女</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="年龄" prop="age" class="form-item-inline">
                <el-input-number
                  v-model="registerForm.age"
                  :min="1"
                  :max="150"
                  placeholder="请输入年龄"
                  class="glass-input-number"
                  size="small"
                />
              </el-form-item>
            </div>
            
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="registerForm.email"
                placeholder="请输入邮箱"
                prefix-icon="Message"
                class="glass-input"
                size="small"
              />
            </el-form-item>
            
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="registerForm.phone"
                placeholder="请输入手机号"
                prefix-icon="Phone"
                class="glass-input"
                size="small"
              />
            </el-form-item>
            
            <el-form-item label="验证码" prop="slideVerify">
              <PuzzleCode
                  v-model:complete="registerForm.slideVerify"
                  :canvas-width="180"
                  :canvas-height="80"
                  :slider-size="20"
                  :border-radius="4"
                  success-text="验证成功！"
                  fail-text="验证失败，请重试"
                  slider-text="请拖动滑块完成验证"
                  @success="handleSlideSuccess"
                  @fail="handleSlideFail"
              />
            </el-form-item>
          </div>
        </div>

        <el-button
          type="primary"
          :loading="loading"
          class="register-button glass-button"
          @click="handleRegister"
        >
          <span v-if="!loading">注册</span>
          <span v-else>注册中...</span>
        </el-button>
      </el-form>

      <div class="register-footer">
        <p>已有账号？<el-link type="primary" @click="goToLogin">立即登录</el-link></p>
      </div>
    </div>

    <AvatarSelection
        v-model="avatarSelectionVisible"
        :current-avatar="registerForm.avatar"
        @avatar-selected="handleAvatarSelected"
    />
  </div>
</template>

<style scoped>
.register-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
  transition: all 0.3s ease;
  padding: 0;
}

/* 暗黑主题 */
.register-container.dark-theme {
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
}

/* 背景装饰 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  overflow: hidden;
}

.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  animation: float 6s ease-in-out infinite;
}

.shape-1 {
  width: 40px;
  height: 40px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 50px;
  height: 50px;
  top: 20%;
  right: 15%;
  animation-delay: 2s;
}

.shape-3 {
  width: 35px;
  height: 35px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

.shape-4 {
  width: 45px;
  height: 45px;
  bottom: 10%;
  right: 10%;
  animation-delay: 1s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-8px) rotate(180deg);
  }
}

/* 主题切换按钮 */
.theme-toggle-wrapper {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
}

/* 注册框 */
.register-box {
  width: 750px;
  max-width: 95vw;
  max-height: 98vh;
  padding: 15px;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
}

.dark-theme .register-box {
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.3);
}

.register-box:hover {
  transform: translateY(-1px);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
}

/* 注册头部 */
.register-header {
  text-align: center;
  margin-bottom: 10px;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 5px;
}

.logo-icon {
  width: 30px;
  height: 30px;
  margin-bottom: 4px;
  color: rgba(255, 255, 255, 0.9);
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.logo-icon:hover {
  transform: scale(1.05);
  background: rgba(255, 255, 255, 0.2);
}

.logo-icon svg {
  width: 18px;
  height: 18px;
}

.register-header h2 {
  font-size: 18px;
  color: rgba(255, 255, 255, 0.95);
  margin: 0;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.register-header p {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.7);
  margin: 0;
  font-weight: 300;
}

/* 表单样式 */
.register-form {
  margin-top: 8px;
}

.register-form :deep(.el-form-item) {
  margin-bottom: 6px;
}

.register-form :deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  font-size: 10px;
  margin-bottom: 2px;
}

/* 两列布局 */
.form-columns {
  display: flex;
  gap: 15px;
  margin-bottom: 8px;
}

.form-column {
  flex: 1;
}

/* 行内布局（性别和年龄） */
.form-row-inline {
  display: flex;
  gap: 8px;
}

.form-item-inline {
  flex: 1;
}

/* 玻璃输入框样式 */
.glass-input {
  transition: all 0.3s ease;
}

.glass-input :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.08);
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 6px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  height: 28px;
}

.glass-input :deep(.el-input__wrapper:hover) {
  background: rgba(255, 255, 255, 0.12);
  border-color: rgba(255, 255, 255, 0.25);
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 4px 12px rgba(255, 255, 255, 0.1);
}

.glass-input :deep(.el-input__wrapper.is-focus) {
  background: rgba(255, 255, 255, 0.15);
  border-color: rgba(64, 158, 255, 0.5);
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 0 2px rgba(64, 158, 255, 0.15), 0 6px 20px rgba(64, 158, 255, 0.2);
}

.glass-input :deep(.el-input__inner) {
  color: rgba(255, 255, 255, 0.95);
  background: transparent;
  font-weight: 400;
  font-size: 11px;
}

.glass-input :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.45);
  font-weight: 300;
}

.glass-input :deep(.el-input__prefix-inner),
.glass-input :deep(.el-input__suffix-inner) {
  color: rgba(255, 255, 255, 0.55);
  transition: color 0.3s ease;
}

.glass-input:hover :deep(.el-input__prefix-inner),
.glass-input:hover :deep(.el-input__suffix-inner) {
  color: rgba(255, 255, 255, 0.75);
}

/* 数字输入框样式 */
.glass-input-number {
  width: 100%;
}

.glass-input-number :deep(.el-input-number) {
  width: 100%;
}

.glass-input-number :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.08);
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 6px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  height: 28px;
}

.glass-input-number :deep(.el-input__wrapper:hover) {
  background: rgba(255, 255, 255, 0.12);
  border-color: rgba(255, 255, 255, 0.25);
}

.glass-input-number :deep(.el-input__wrapper.is-focus) {
  background: rgba(255, 255, 255, 0.15);
  border-color: rgba(64, 158, 255, 0.5);
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 0 2px rgba(64, 158, 255, 0.15), 0 6px 20px rgba(64, 158, 255, 0.2);
}

.glass-input-number :deep(.el-input__inner) {
  color: rgba(255, 255, 255, 0.95);
  background: transparent;
  font-size: 11px;
}

/* 单选框样式 */
.glass-radio-group {
  display: flex;
  gap: 10px;
}

.glass-radio :deep(.el-radio__label) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  font-size: 11px;
}

.glass-radio :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: rgba(64, 158, 255, 0.8);
  border-color: rgba(64, 158, 255, 0.8);
}

.glass-radio :deep(.el-radio__inner) {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.3);
  width: 9px;
  height: 9px;
}

.glass-radio:hover :deep(.el-radio__inner) {
  border-color: rgba(64, 158, 255, 0.5);
}

/* 注册按钮 */
.glass-button {
  width: 100%;
  height: 32px;
  font-size: 12px;
  font-weight: 600;
  border-radius: 8px;
  background: rgba(64, 158, 255, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  margin-top: 8px;
}

.glass-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.glass-button:hover::before {
  left: 100%;
}

.glass-button:hover {
  background: rgba(64, 158, 255, 0.9);
  transform: translateY(-1px);
  box-shadow: 0 6px 15px rgba(64, 158, 255, 0.3);
}

.glass-button:active {
  transform: translateY(0);
}

/* 注册底部 */
.register-footer {
  text-align: center;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.register-footer p {
  color: rgba(255, 255, 255, 0.7);
  font-size: 10px;
  margin: 0;
}

.register-footer .el-link {
  color: rgba(64, 158, 255, 0.9);
  font-weight: 500;
  font-size: 10px;
}

/* 暗黑主题下的特殊样式 */
.dark-theme .register-header h2 {
  color: rgba(255, 255, 255, 0.95);
}

.dark-theme .register-header p {
  color: rgba(255, 255, 255, 0.6);
}

.dark-theme .glass-input :deep(.el-input__wrapper) {
  background: rgba(0, 0, 0, 0.15);
  border-color: rgba(255, 255, 255, 0.08);
  box-shadow: inset 0 1px 3px rgba(255, 255, 255, 0.05);
}

.dark-theme .glass-input :deep(.el-input__wrapper:hover) {
  background: rgba(0, 0, 0, 0.25);
  border-color: rgba(255, 255, 255, 0.15);
  box-shadow: inset 0 1px 3px rgba(255, 255, 255, 0.05), 0 4px 12px rgba(0, 0, 0, 0.2);
}

.dark-theme .glass-input :deep(.el-input__wrapper.is-focus) {
  background: rgba(0, 0, 0, 0.3);
  border-color: rgba(64, 158, 255, 0.6);
  box-shadow: inset 0 1px 3px rgba(255, 255, 255, 0.05), 0 0 0 2px rgba(64, 158, 255, 0.2), 0 6px 20px rgba(64, 158, 255, 0.3);
}

.dark-theme .glass-input :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.35);
}

.dark-theme .glass-input :deep(.el-input__prefix-inner),
.dark-theme .glass-input :deep(.el-input__suffix-inner) {
  color: rgba(255, 255, 255, 0.45);
}

.dark-theme .glass-input:hover :deep(.el-input__prefix-inner),
.dark-theme .glass-input:hover :deep(.el-input__suffix-inner) {
  color: rgba(255, 255, 255, 0.65);
}

.dark-theme .floating-shape {
  background: rgba(255, 255, 255, 0.05);
}

.dark-theme .glass-input-number :deep(.el-input__wrapper) {
  background: rgba(0, 0, 0, 0.15);
  border-color: rgba(255, 255, 255, 0.08);
}

.dark-theme .glass-input-number :deep(.el-input__wrapper:hover) {
  background: rgba(0, 0, 0, 0.25);
  border-color: rgba(255, 255, 255, 0.15);
}

.dark-theme .glass-input-number :deep(.el-input__wrapper.is-focus) {
  background: rgba(0, 0, 0, 0.3);
  border-color: rgba(64, 158, 255, 0.6);
}

.dark-theme .glass-radio :deep(.el-radio__inner) {
  background: rgba(0, 0, 0, 0.2);
  border-color: rgba(255, 255, 255, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-box {
    width: 95%;
    padding: 12px;
    margin: 2px;
  }

  .theme-toggle-wrapper {
    top: 5px;
    right: 5px;
  }

  .floating-shape {
    display: none;
  }

  .form-columns {
    flex-direction: column;
    gap: 0;
  }

  .form-row-inline {
    flex-direction: column;
    gap: 0;
  }

  .form-item-inline {
    flex: none;
  }
}

@media (max-width: 480px) {
  .register-header h2 {
    font-size: 16px;
  }

  .register-box {
    padding: 10px;
  }
}
</style>
